# -*- coding: utf-8 -*-
import logging
import sys
from bs4 import BeautifulSoup
from datetime import datetime, timedelta
from dateutil import parser
import time

import os
import requests

# add up one level dir into sys path
sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common.lottery.handler import crawl_from_opencai
from common.lottery.cyclical.cq_lf.db.activity import fullfill_result
from common.lottery import LOTTERY_TYPE, OPENCAI_LOTTERY_TYPES
from common.timer import TIMER_EVENT_TYPE, TimerEvent
from common.utils import tz


def _get_default_date():
    date = tz.utc_to_local(datetime.utcnow())
    # 如果是第二天刚开始的时候，需要去爬前一天最后几期的结果
    if date.hour == 0 and date.minute < 3:
        date -= timedelta(days=1)
    return date


def crawl_from_168(date=None):
    calc_date = date or _get_default_date()
    url = 'http://api.1680210.com/klsf/getHistoryLotteryInfo.do?date=%s&lotCode=10009' % calc_date.strftime('%Y-%m-%d')
    try:
        response = requests.get(url, timeout=10)
    except Exception as e:
        raise e
    if response.status_code != 200:
        raise RuntimeError('request error')
    _parse_and_fill_168(response.json(), url)


def _parse_and_fill_168(data, refer):
    if data['errorCode'] == 0:
        nodes = data['result']['data']
        for node in nodes:
            phase = node['preDrawIssue']  # 期號
            number = node['preDrawCode']  # 開獎結果
            activity = fullfill_result(phase, number, refer)
            if activity:
                TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {  # 走勢圖
                    'number': number, 'term': phase,
                    'activity_type': LOTTERY_TYPE.CQ_LF}, tz.now_ts()
                                  )
                TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {  # 中獎結算
                    'number': number, 'term': phase,
                    'activity_type': LOTTERY_TYPE.CQ_LF}, tz.now_ts())


def crawl_from_official_now():
    url = 'http://www.cqcp.net/game/xync/yu.aspx'
    try:
        response = requests.get(url, timeout=5)
    except Exception as e:
        raise e
    if response.status_code != 200:
        raise RuntimeError('request error')
    response = response.text.split('|')

    phase = '20' + response[1]  # 期號, 20xx 年
    number = response[0].replace('-', ',')  # 開獎結果

    activity = fullfill_result(phase, number, url)
    if activity:
        TimerEvent.submit(TIMER_EVENT_TYPE.CALC_STATS, {
            'number': number, 'term': phase,
            'activity_type': LOTTERY_TYPE.CQ_LF}, tz.now_ts())
        TimerEvent.submit(TIMER_EVENT_TYPE.ACTIVITY_ANNOUNCE, {
            'number': number, 'term': phase,
            'activity_type': LOTTERY_TYPE.CQ_LF}, tz.now_ts())


def main(d):
    while True:
        try:
            crawl_from_opencai(LOTTERY_TYPE.CQ_LF)
        except Exception as e:
            logging.exception(u'%s error: %s' % (OPENCAI_LOTTERY_TYPES.get(LOTTERY_TYPE.CQ_SSC), e))
        if d:
            break
        time.sleep(60)


if __name__ == '__main__':
    date = sys.argv[1] if len(sys.argv) > 1 else None
    main(date)
